<template>
  <view class="container">
    <scroll-view class="scroll-view" scroll-y="true">
      <view v-for="(message, index) in messages" :key="index" class="message">
        <view class="message-time">{{ message.time }}</view>
        <view class="message-content" :class="{'right': message.isMe}">
          {{ message.content }}
        </view>
      </view>
    </scroll-view>
    <view class="input-box">
      <input class="input" v-model="inputText" @keyup.enter="sendMessage" placeholder="请输入消息" />
      <button class="button" @click="sendMessage">发送</button>
    </view>
  </view>
</template>

<script>
  export default {
    data() {
      return {
        inputText: '',
        messages: [],
        socket: null,
      }
    },
    onLoad() {
      // 创建WebSocket连接
      // this.socket = uni.createSocket({
      //   url: 'ws://localhost:9998/socket',
      // })
	  // this.socket = new WebSocket("ws://localhost:9998/socket");
      // 监听WebSocket连接打开事件
      this.socket.onOpen(() => {
        // 发送注册信息
        this.socket.send({
          type: 'register',
          data: {
            toUserId: '123', // 私聊对象的userId
          },
        })
      })
      // 监听WebSocket收到消息事件
      this.socket.onMessage((res) => {
        const message = JSON.parse(res.data)
        // 解析消息内容，添加到messages数组中
        const newMessage = {
          time: new Date(message.time).toLocaleTimeString(),
          content: message.content,
          isMe: message.fromUserId === 'myUserId', // 是否是自己发送的消息
        }
        this.messages.push(newMessage)
      })
    },
    methods: {
      // 发送消息
      sendMessage() {
        if (!this.inputText.trim()) return
        this.socket.send({
          type: 'message',
          data: {
            content: this.inputText.trim(),
            toUserId: '123', // 私聊对象的userId
          },
        })
        this.inputText = ''
      }
    },
	onUnload() {
	  this.socket.close()
	}
}
</script>

<style scoped>

</style>